package com.chen.jwt.interceptors;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.jwt.annotation.PassToken;
import com.chen.jwt.annotation.UserLoginToken;
import com.chen.jwt.config.ResultCode;
import com.chen.jwt.enumToken.Token;
import com.chen.jwt.pojo.Users;
import com.chen.jwt.service.User;
import com.chen.jwt.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
 * @author 12926
 */
@Component
@SuppressWarnings("all")
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    User user;
    // 请求前到达之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
            throws Exception {
        // 从请求头获取 token
        String token = request.getHeader(Token.TOKEN);
        //首先映射是不是方法，如果不是则返回
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // token 验证失败后的返回信息
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                if (StrUtil.isBlank(token)) {
                    throw new RuntimeException(String.valueOf(ResultCode.NO_TOKEN));
                }
                // 获取 token 中的 user id
                int userId;
                try {
                    DecodedJWT decode = JWT.decode(token);
                    String id = decode.getClaim(Token.ID).asString();
                    userId = Integer.parseInt(id);

                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                System.out.println(userId);
                Users users = user.findUserById(userId);
                if (users == null) {
                    throw new RuntimeException(String.valueOf(ResultCode.USER_LONGIN_EXIST));
                }
                try {
                    // JWT 工具包验证 token
                    JWTUtils.verify(token);
                    return true;
                } catch (TokenExpiredException e) {
                    throw new RuntimeException("Token已经过期!!!");
                } catch (SignatureVerificationException e){
                    throw new RuntimeException("签名错误!!!");
                } catch (AlgorithmMismatchException e){
                    throw new RuntimeException("加密算法不匹配!!!");
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("无效token~~");
                }
            }
        }
        return true;
    }
}
